package com.ittao.taoaicodemother.manage.storage.strategy.impl;

import com.ittao.taoaicodemother.manage.storage.enums.StorageType;
import com.ittao.taoaicodemother.manage.storage.strategy.FileStorageStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.springframework.util.FileSystemUtils;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 本地文件存储策略实现
 * 使用本地文件系统进行文件存储
 * 路径格式：tmp/{userId}/code_output/vue_project_{appId}/{具体文件}
 *          tmp/{userId}/code_deploy/{deployKey}/{具体文件}
 */
@Slf4j
@Component
public class LocalFileStorageStrategy implements FileStorageStrategy {

    private static final String BASE_PATH = System.getProperty("user.dir") + File.separator + "tmp";

    @Override
    public StorageType getStorageType() {
        return StorageType.LOCAL;
    }

    @Override
    public void writeFile(String filePath, byte[] content) throws IOException {
        Path path = Paths.get(filePath);
        // 确保父目录存在
        Files.createDirectories(path.getParent());
        Files.write(path, content);
        log.debug("本地文件写入成功: {}", filePath);
    }

    @Override
    public Resource readFile(String filePath) throws IOException {
        Path path = Paths.get(filePath);
        if (!Files.exists(path)) {
            throw new IOException("文件不存在: " + filePath);
        }
        return new FileSystemResource(path);
    }

    @Override
    public void deleteFile(String filePath) throws IOException {
        Path path = Paths.get(filePath);
        if (Files.exists(path)) {
            if (Files.isDirectory(path)) {
                FileSystemUtils.deleteRecursively(path);
            } else {
                Files.delete(path);
            }
            log.debug("本地文件删除成功: {}", filePath);
        }
    }

    @Override
    public String buildCodeOutputPath(String userId, String fileName) {
        // 本地路径格式：tmp/{userId}/code_output/vue_project_{appId}/{具体文件}
        // 这里fileName应该是vue_project_{appId}格式
        return String.format("%s%s%s%scode_output%s%s",
                BASE_PATH, File.separator, userId, File.separator, File.separator, fileName);
    }

    @Override
    public String buildCodeDeployPath(String userId, String deployKey) {
        // 本地路径格式：tmp/{userId}/code_deploy/{deployKey}/{具体文件}
        return String.format("%s%s%s%scode_deploy%s%s",
                BASE_PATH, File.separator, userId, File.separator, File.separator, deployKey);
    }

    @Override
    public String buildDisplayPath(String baseDirPath, String userId, String appId, String codeType) {
        // 本地存储：返回绝对文件路径
        return new File(baseDirPath).getAbsolutePath();
    }
}